package com.baosight.sczx.zm.cl.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baosight.iplat4j.core.ei.EiConstant;
import com.baosight.iplat4j.core.ei.EiInfo;
import com.baosight.iplat4j.core.threadlocal.UserSession;
import com.baosight.iplat4j.ep.ServiceEPBase;
import com.baosight.sczx.common.zm.basetools.StaticTools;
import com.baosight.sczx.common.zm.basetools.TablePk;
import com.baosight.sczx.common.zm.cInterface.Department;
import com.baosight.sczx.common.zm.cInterface.User;
import com.baosight.sczx.common.zm.cInterface.cc.Qualitystandard;
import com.baosight.sczx.common.zm.cInterface.cc._5ExamineClassify;
import com.baosight.sczx.common.zm.cInterface.cf.MessageUtil;
import com.baosight.sczx.common.zm.cInterface.cf.Penalty;
import com.baosight.sczx.common.zm.cInterface.cl.OperationHistory;
import com.baosight.sczx.common.zm.cInterface.cl.RiskHandle;
import com.baosight.sczx.common.zm.cInterface.cl.RoundCheckWorkNote;
import com.baosight.sczx.common.zm.cInterface.cs.InitialData;
import com.baosight.sczx.common.zm.cInterface.cs.WorkSchedule;
import com.baosight.sczx.zm.cl.domain.ZMCLRiskHandleProcess_x;
import com.baosight.sczx.zm.cl.domain.ZMCLRiskRecord;

/**
 * 隐患处理模块
 * 待处理隐患记录
 * <p>Title: ServiceZMCL70.java</p>
 * <p>Description: </p>
 * <p>Copyright: Baosight Software LTD.co Copyright (c) 2002</p>
 * <p>Company: Baosight Software</p>
 * @author 严洪浩
 * @version 1.0
 * <pre>Histroy:
 *          2011-8-5 上午07:48:33  严洪浩  Create
 *</pre>
 */
public class ServiceZMCL70 extends ServiceEPBase {
	
	/**
	 * 初始进入
	 * <p>Function: initLoad</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCL70</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-8-5上午07:50:22 严洪浩
	 * </p>
	 *
	 */
	@Override
	public EiInfo initLoad(EiInfo inInfo) {
		inInfo.addBlock(EiConstant.resultBlock).set("showCount", "true");//如果不加这个，翻页的统计和显示是错误的
		EiInfo outInfo = this.query(inInfo);
		
		outInfo.addBlock(Department.getInstance().getConstructionUnit("cmes.cl.orgName", "orgCode", "orgName", false));//组织机构
		outInfo.addBlock(User.getInstance().getConstructionStaff("cmes.cl.empName", "empCode", "empName", true));//人员
		outInfo.addBlock(InitialData.getInstance().getEiBlockByNo("cmes.cl.riskSource", false));//隐患来源
		outInfo.addBlock(InitialData.getInstance().getEiBlockByNo("cmes.cl.riskLevel", false));//隐患级别
		outInfo.addBlock(InitialData.getInstance().getEiBlockByNo("cmes.cl.riskClassify", false));//隐患分类
		outInfo.addBlock(WorkSchedule.getWorkScheduleBlock("cmes.cl.riskWorknum", false));//隐患班次
		//outInfo.addBlock(WorkingFace.getAllWorkingFace("cmes.cl.workface", true));//所在工作面
		//outInfo.addBlock(RoadWay.getAllRoadWay("cmes.cl.path", true));//所在巷道
		outInfo.addBlock(RoundCheckWorkNote.getAllNoteCode("cmes.cl.workNote", true));//巡检工单
		outInfo.addBlock(Qualitystandard.getQualityStandardItems("cmes.cl.quality", "在用", true));//质量标准化分类
		outInfo.addBlock(_5ExamineClassify.get5examineClassify("cmes.cl.examine", "在用", true));//五个到位分类
		outInfo.addBlock(InitialData.getInstance().getEiBlockByNo("cmes.cl.penaltyType"));//罚款分类
		
		outInfo.set("fdManageDepartmentId", UserSession.getInSessionProperty("orgCode"));//用户所在单位ID
		outInfo.set("fdManageDepartment", UserSession.getInSessionProperty("orgName"));//用户所在单位
		
		outInfo.set("fdRecheckPeopleId", UserSession.getUserId());//复查人ID
		outInfo.set("fdRecheckPeople", UserSession.getInSessionProperty("UserCname"));//复查人
		
		return outInfo;
	}
	
	/**
	 * 查询
	 * <p>Function: query</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCL70</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-8-5上午07:51:16 严洪浩
	 * </p>
	 *
	 */
	@Override
	public EiInfo query(EiInfo inInfo) {
		if(inInfo.getBlock(EiConstant.queryBlock) == null){
			StaticTools.setQueryParameters(inInfo, "fdEndDate", StaticTools.getDate(), true);//截止日期
		}
		
		//StaticTools.setQueryParameters(inInfo, "fdManageDepartmentId", UserSession.getInSessionProperty("orgCode"), true);//主管部门
		StaticTools.setQueryParameters(inInfo, "isHandling", "yes", true);//所有未作废\关闭的隐患
		EiInfo outInfo = super.query(inInfo, "ZMCLRiskRecord.query", new ZMCLRiskRecord());
		
		return outInfo;
	}
	
	/**
	 * 安全管理部门新增隐患
	 * 非 井口/批量新增
	 * <p>Function: insert</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCL70</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-8-5下午02:54:07 严洪浩
	 * </p>
	 *
	 */
	@Override
	public EiInfo insert(EiInfo inInfo) {
		//校验编号是否重复
		boolean validate = this.validate(inInfo, "ZMCLRiskRecord.validate", new HashMap<String, String>());
		
		if(validate) {
			return inInfo;
		}
		else {
			String fdKeyId = TablePk.getInstance().getNextValue("T_CL_RISK_RECORD");//隐患记录ID
			String fdCheckPeopleId = inInfo.getBlock("result").getCellStr(0, "fdCheckPeopleId");//检查人ID
			
			inInfo.getBlock("result").setCell(0, "fdKeyId", fdKeyId);//ID
			inInfo.getBlock("result").setCell(0, "fdIsRepeat", "否");//是否重复隐患
			inInfo.getBlock("result").setCell(0, "fdIsPenalty", "否");//是否罚款
			inInfo.getBlock("result").setCell(0, "fdStatus", "未处理");//状态
			inInfo.getBlock("result").setCell(0, "fdCheckPeople", fdCheckPeopleId);//检查人
			inInfo.getBlock("result").setCell(0, "fdCreateTime", StaticTools.getDateTime());//创建时间
			inInfo.getBlock("result").setCell(0, "fdCreateUserId", UserSession.getUserId());//录入人ID
			inInfo.getBlock("result").setCell(0, "fdCreateUser", UserSession.getInSessionProperty("UserCname"));//录入人
			
			EiInfo outInfo = super.insert(inInfo, "ZMCLRiskRecord.insert");
			boolean insertValue = OperationHistory.InsertOperationHistory(inInfo, "隐患","新增");//新增隐患处理记录
			if(!insertValue) {
				outInfo.setStatus(-1);
				outInfo.setMsg("插入操作记录失败！");
				return outInfo;
			}
			return outInfo;
		}
	}
	
	/**
	 * 安全管理部门修改隐患
	 * 非 井口
	 * <p>Function: update</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCL70</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-8-8上午07:35:09 严洪浩
	 * </p>
	 *
	 */
	@Override
	public EiInfo update(EiInfo inInfo) {
		//校验编号是否重复
		Map<String, String> _args = new HashMap<String, String>();
		_args.put("fdKeyId", inInfo.getBlock("result").getCellStr(0, "fdKeyId"));
		
		boolean validate = this.validate(inInfo, "ZMCLRiskRecord.validate", _args);
		
		if(validate) {
			return inInfo;
		}
		else {
			String fdCheckPeopleId = inInfo.getBlock("result").getCellStr(0, "fdCheckPeopleId");//检查人ID
			
			inInfo.getBlock("result").setCell(0, "fdIsRepeat", "否");//是否重复隐患
			inInfo.getBlock("result").setCell(0, "fdIsPenalty", "否");//是否罚款
			inInfo.getBlock("result").setCell(0, "fdCheckPeople", fdCheckPeopleId);//检查人
			inInfo.getBlock("result").setCell(0, "fdCreateTime", StaticTools.getDateTime());//创建时间
			inInfo.getBlock("result").setCell(0, "fdCreateUserId", UserSession.getUserId());//录入人ID
			inInfo.getBlock("result").setCell(0, "fdCreateUser", UserSession.getInSessionProperty("UserCname"));//录入人
			
			EiInfo outInfo = super.update(inInfo, "ZMCLRiskRecord.update");
			boolean insertValue = OperationHistory.InsertOperationHistory(inInfo, "隐患","修改");//新增隐患处理记录
			if(!insertValue) {
				outInfo.setStatus(-1);
				outInfo.setMsg("插入操作记录失败！");
				return outInfo;
			}
			return outInfo;
		}
	}
	
	/**
	 * 隐患处理
	 * <p>Function: handle</p>
	 * <p>Description: </p>
	 * <p>return value:EiInfo</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-8-15上午04:31:35 严洪浩
	 *    2011-8-19  modified by wangkun 加入消息发送
	 * </p>
	 *
	 */
	public EiInfo handle(EiInfo inInfo) {
		String fdRiskHandleId = TablePk.getInstance().getNextValue("T_CL_RISK_HANDLE");//隐患处理记录ID
		boolean insertValue = RiskHandle.Insert(inInfo, fdRiskHandleId);//新增隐患处理记录
		
		EiInfo outInfo = new EiInfo();
		if(insertValue) {
			//隐患处理新增成功
			inInfo.getBlock("result").setCell(0, "fdStatus", "未查收");
			outInfo = super.update(inInfo, "ZMCLRiskRecord.modifyHandle");//改变隐患记录状态
			
			outInfo.set("fdRiskHandleId", fdRiskHandleId);
			outInfo.addBlock(InitialData.getInstance().getEiBlockByNo("cmes.cl.penaltyType"));//罚款分类
		}
		else {
			outInfo.setStatus(-1);
			outInfo.setMsg("隐患处理失败！");
			return outInfo;
		}

		//发送消息
		if(insertValue) {
			String fdDepartmentId = inInfo.getBlock(EiConstant.resultBlock).getCellStr(0, "fdDepartmentId");
			String fdResponsibilityPeople = inInfo.getBlock(EiConstant.resultBlock).getCellStr(0, "fdResponsibilityPeople");
			
			if(fdResponsibilityPeople.length()>60)
			{
				fdResponsibilityPeople = fdResponsibilityPeople.substring(0, 60) + "...";
			}
			
			MessageUtil messageUtil = new MessageUtil();
			messageUtil.setDao(dao);
			int result = messageUtil.insertIntoMessageCache("下达关于责任人"+fdResponsibilityPeople+"的隐患整改通知", "ZMCL73", fdDepartmentId, "", 1);
			
			if(result != 1)
			{
				System.out.println("消息发送失败: "+result);
			}
		}
		//end
		
		return outInfo;
	}
	
	/**
	 * 罚款
	 * <p>Function: penalty</p>
	 * <p>Description: </p>
	 * <p>return value:EiInfo</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-8-7下午02:36:58 严洪浩
	 *    2011-8-19 modified by wangkun  增加发送消息功能
	 * </p>
	 *
	 */
	public EiInfo penalty(EiInfo inInfo) {
		String fdKeyId = TablePk.getInstance().getNextValue("T_CF_PENALTY");//罚款单ID
		String fdRiskRecordId = inInfo.getBlock("result").getCellStr(0, "fdRiskRecordId");//隐患记录ID
		String fdRiskHandleId = inInfo.getCellStr("result", 0, "fdRiskHandleId");//隐患处理记录ID
		
		StaticTools.setQueryParameters(inInfo, "fdKeyId", fdRiskRecordId, true);//隐患记录ID
		EiInfo _tempInfo = super.query(inInfo, "ZMCLRiskRecord.query", new ZMCLRiskRecord());
		
		String fdIsPenalty = _tempInfo.getBlock("result").getCellStr(0, "fdIsPenalty");//是否罚款
		String fdPenaltyIds = _tempInfo.getBlock("result").getCellStr(0, "fdPenaltyIds");//罚款记录ID'S
		
		if("否".equals(fdIsPenalty)) {
			inInfo.setCell("result", 0, "fdIsPenalty", "是(1)");
			inInfo.setCell("result", 0, "fdPenaltyIds", fdKeyId);
		}
		else {
			String _number = fdIsPenalty.substring(fdIsPenalty.indexOf("(")+1, fdIsPenalty.indexOf(")"));
			
			int number = 2;//默认为2
			try {
				number = Integer.parseInt(_number) + 1;
			} catch (NumberFormatException e) {
				System.out.println("隐患罚款时数据转换错误 : " + e.getMessage());
			}
			
			inInfo.setCell("result", 0, "fdIsPenalty", "是("+number+")");
			inInfo.setCell("result", 0, "fdPenaltyIds", fdPenaltyIds+","+fdKeyId);
		}
		
		//更新隐患记录
		EiInfo outInfo = super.update(inInfo, "ZMCLRiskRecord.modifyPenalty");
		
		//更新隐患处理记录
		//直接罚款不进行此操作
		if(null != fdRiskHandleId && !"".equals(fdRiskHandleId.trim())) {
			inInfo.setCell("result", 0, "fdPenaltyId", fdKeyId);
			RiskHandle.Update(inInfo);
		}
		
		//新增罚款记录
		Penalty.Insert(inInfo, fdKeyId);
		
		return outInfo;
	}
	
	/**
	 * 隐患处理
	 * 填写复查意见
	 * <p>Function: recheck</p>
	 * <p>Description: </p>
	 * <p>return value:EiInfo</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-8-8上午06:21:56 严洪浩
	 *    2011-8-19 modified by wangkun 加入消息发送部分
	 * </p>
	 *
	 */
	@SuppressWarnings("rawtypes")
	public EiInfo recheck(EiInfo inInfo) {
		//先检查是否已经处理  得到隐患 隐患处理 隐患整改 隐患复查的ID
		//判断是否复查
		String fdRiskRecordId = inInfo.getBlock("result").getCellStr(0, "fdKeyId");//隐患记录ID
		String fdIsRedo = inInfo.getBlock("result").getCellStr(0, "fdIsRedo");//是否重新整改
		String fdIsRepeat = inInfo.getBlock("result").getCellStr(0, "fdIsRepeat");//是否重复隐患
		
		boolean value = this.canRecheck(fdRiskRecordId);//是否已经被关闭
		
		if(value) {
			if("是".equals(fdIsRedo)) {
				//重新整改 更改状态 修改是否重复隐患字段
				inInfo.setCell("result", 0, "fdStatus", "未处理");
				
				int number = 2;
				if(!"否".equals(fdIsRepeat)) {
					try {
						String _tempNumber = fdIsRepeat.substring(fdIsRepeat.indexOf("(") + 1, fdIsRepeat.indexOf(")"));
						number = Integer.parseInt(_tempNumber) + 1;
					} catch (Exception e) {
						System.out.println("隐患处理模块,填写复查意见异常: "+ e.getMessage());
					}
					inInfo.setCell("result", 0, "fdIsRepeat", "是("+number+")");
				}
				else {
					inInfo.setCell("result", 0, "fdIsRepeat", "是(1)");
				}
			}
			else {
				inInfo.setCell("result", 0, "fdStatus", "关闭");
				boolean insertValue = OperationHistory.InsertOperationHistory(inInfo, "隐患","关闭");//新增隐患处理记录
				if(!insertValue) {
					inInfo.setStatus(-1);
					inInfo.setMsg("插入操作记录失败！");
					return inInfo;
				}
			}
			
			EiInfo outInfo = super.update(inInfo, "ZMCLRiskRecord.modifyRecheck");//更改隐患记录数据
			if(outInfo.getStatus() != -1) {
				Map<String, String> _args = new HashMap<String, String>();
				_args.put("fdStatus", "1");
				_args.put("fdRiskRecordId", fdRiskRecordId);
				
				List _result = dao.query("ZMCLRiskHandleProcess_x.query", _args);
				if(_result.size() > 0) {
					ZMCLRiskHandleProcess_x process = (ZMCLRiskHandleProcess_x)_result.get(0);
					
					inInfo.setCell("result", 0, "fdKeyId", TablePk.getInstance().getNextValue("T_CL_RISK_REVIEW"));//ID
					inInfo.setCell("result", 0, "fdRiskRecordId", process.getFdRiskRecordId());//隐患记录ID
					inInfo.setCell("result", 0, "fdRiskHandleId", process.getFdRiskHandleId());//隐患处理ID
					inInfo.setCell("result", 0, "fdRiskModifyId", process.getFdRiskModifyId());//隐患整改ID
					inInfo.setCell("result", 0, "fdRecheckerDepartmentId", UserSession.getInSessionProperty("orgCode"));//复查部门ID
					inInfo.setCell("result", 0, "fdRecheckerDepartment", UserSession.getInSessionProperty("orgName"));//复查部门
					inInfo.setCell("result", 0, "fdCreateTime", StaticTools.getDateTime());//创建时间

					super.insert(inInfo, "ZMCLRiskReview.insert");//新增复查记录
					boolean insertValue = OperationHistory.InsertOperationHistory(inInfo, "隐患","复查");//新增隐患处理记录
					if(!insertValue) {
						inInfo.setStatus(-1);
						inInfo.setMsg("插入操作记录失败！");
						return inInfo;
					}
					RiskHandle.InvalidOrClose( process.getFdRiskRecordId());//更新隐患处理记录状态
					
					//发送消息
					if("是".equals(fdIsRedo)) {
						String fdDepartmentId = inInfo.getBlock("result").getCellStr(0, "fdDepartmentId");//责任部门
						String fdResponsibilityPeople = inInfo.getBlock("result").getCellStr(0, "fdResponsibilityPeople");//责任人
						
						if(fdResponsibilityPeople.length()>60)
						{
							fdResponsibilityPeople = fdResponsibilityPeople.substring(0, 60) + "...";
						}
						
						MessageUtil messageUtil = new MessageUtil();
						messageUtil.setDao(dao);
						int result = messageUtil.insertIntoMessageCache("下达关于责任人"+fdResponsibilityPeople+"的隐患重新整改通知", "ZMCL73", fdDepartmentId, "", 1);
						
						if(result != 1)
						{
							System.out.println("消息发送失败:code:"+result);
						}
					}
					//end
				}
			}
			
			return outInfo;
		}
		else {
			inInfo.setStatus(-1);
			inInfo.setMsg("该隐患已经关闭或作废，请刷新纪录！");
			return inInfo;
		}
	}
	
	/**
	 * 延期
	 * <p>Function: invalid</p>
	 * <p>Description: </p>
	 * <p>return value:EiInfo</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-8-8下午02:33:27 严洪浩
	 * </p>
	 *
	 */
	public EiInfo delay(EiInfo inInfo) {
		EiInfo _temp = super.update(inInfo, "ZMCLRiskRecord.delay");//延期
		boolean insertValue = OperationHistory.InsertOperationHistory(inInfo, "隐患","延期");//新增隐患处理记录
		if(!insertValue) {
			_temp.setStatus(-1);
			_temp.setMsg("插入操作记录失败！");
			return _temp;
		}
		EiInfo outInfo = this.query(inInfo);
        outInfo.setMsg(_temp.getMsg());
        outInfo.setDetailMsg(_temp.getDetailMsg());
		return outInfo;
	}
	
	/**
	 * 作废
	 * <p>Function: invalid</p>
	 * <p>Description: </p>
	 * <p>return value:EiInfo</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-8-8下午02:33:27 严洪浩
	 * </p>
	 *
	 */
	public EiInfo invalid(EiInfo inInfo) {
		String fdKeyId = inInfo.getBlock("result").getCellStr(0, "fdKeyId");//隐患记录ID
		RiskHandle.InvalidOrClose(fdKeyId);//更改隐患处理状态
		
		EiInfo _temp = super.update(inInfo, "ZMCLRiskRecord.modifyInvalid");//作废
		boolean insertValue = OperationHistory.InsertOperationHistory(inInfo, "隐患","作废");//新增隐患处理记录
		if(!insertValue) {
			_temp.setStatus(-1);
			_temp.setMsg("插入操作记录失败！");
			return _temp;
		}
		EiInfo outInfo = this.query(inInfo);
        outInfo.setMsg(_temp.getMsg());
        outInfo.setDetailMsg(_temp.getDetailMsg());
		return outInfo;
	}

	/**
	 * 关闭
	 * <p>Function: invalid</p>
	 * <p>Description: </p>
	 * <p>return value:EiInfo</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-8-8下午02:33:27 严洪浩
	 * </p>
	 *
	 */
	public EiInfo close(EiInfo inInfo) {
		String fdKeyId = inInfo.getBlock("result").getCellStr(0, "fdKeyId");//隐患记录ID
		RiskHandle.InvalidOrClose(fdKeyId);//更改隐患处理状态
		
		EiInfo _temp = super.update(inInfo, "ZMCLRiskRecord.modifyClose");//关闭
		boolean insertValue = OperationHistory.InsertOperationHistory(inInfo, "隐患","关闭");//新增隐患处理记录
		if(!insertValue) {
			_temp.setStatus(-1);
			_temp.setMsg("插入操作记录失败！");
			return _temp;
		}
		EiInfo outInfo = this.query(inInfo);
        outInfo.setMsg(_temp.getMsg());
        outInfo.setDetailMsg(_temp.getDetailMsg());
		return outInfo;
	}
	
	/**
	 * 校验隐患编号的唯一性
	 * <p>Function: validate</p>
	 * <p>Description: 校验隐患编号的唯一性</p>
	 * <p>return value:boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-4-12上午11:14:21 张小飞
	 * </p>
	 *
	 */
	private boolean validate(EiInfo inInfo, String sqlName, Map<String, String> params) {
		if(params == null) {
			params = new HashMap<String, String>();
		}
		String fdRiskCode = inInfo.getBlock(EiConstant.resultBlock).getCellStr(0, "fdRiskCode");
		params.put("fdRiskCode", fdRiskCode);
		
		List<?> result = dao.query(sqlName, params);
		if(result!=null && result.size() > 0) {
			inInfo.setStatus(-1);
			inInfo.setMsg("提交失败，编号重复！");
			return true;
		}
		return false;
	}
	
	/**
	 * 是否能复查，避免同时操作时
	 * 该记录已经被复查
	 * <p>Function: canRecheck</p>
	 * <p>Description: </p>
	 * <p>return value:boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-10-12上午06:08:19 严洪浩
	 * </p>
	 *
	 */
	private boolean canRecheck(String fdKeyId) {
		Map<String, String> _argMap = new HashMap<String, String>();
		_argMap.put("fdRiskRecordId", fdKeyId);
		
		List<?> _result = dao.query("ZMCLRiskHandle.canRecheck", _argMap);
		
		if(_result.size() > 0) {
			return true;
		}
		else {
			return false;
		}
	}
}
